package com.ruoyi.controller;

import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.util.List;
import java.util.UUID;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Null;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.github.pagehelper.PageHelper;
import com.ruoyi.domain.dto.BookDto;
import com.ruoyi.pojo.dto.Dict;
import com.ruoyi.pojo.vo.BookVo;
import com.ruoyi.utils.QiniuImageUploader;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.page.PageDomain;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.domain.Book;
import com.ruoyi.service.IBookService;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 图书管理Controller
 *
 * @author qyb
 * @date 2023-12-26
 */
@RestController
@RequestMapping("/bookManage")
public class BookController extends BaseController
{
    @Autowired
    private IBookService service;
    @Autowired
    private QiniuImageUploader qiniuImageUploader;

    @Value("${ruoyi.profile}")
    private String uploadPath;


    /**
     * 图书增加
     * @param bookDto
     * @return
     */
    @RequestMapping("addBook")
    @Log(title = "增加图书",businessType = BusinessType.INSERT)
    public AjaxResult addBook(@Validated @RequestBody BookDto bookDto){
        return service.addBook(bookDto);
    }

    /**
     *
     * @param pageDomain
     * @param searchByName
     * @return
     */
    @RequestMapping("searchBook")
    public TableDataInfo searchBook(@RequestBody @Null PageDomain pageDomain, @RequestBody String searchByName){
//        PageHelper.startPage(pageDomain.getPageNum(), pageDomain.getPageSize());
        List<BookVo> list = service.searchBook(searchByName,pageDomain.getPageSize(),pageDomain.getPageNum());
        int total = service.getTotal(searchByName);
        return new TableDataInfo(list,total);
    }
    @GetMapping("selectBookById")
    public  AjaxResult selectBookById(Book book){
        return AjaxResult.success(service.selectBookById(Math.toIntExact(book.getBookId())));
    }
    /**
     * 删除图书
     * @param ids
     * @return
     */
    @RequestMapping("deleteBook")
    @Log(title = "删除图书",businessType = BusinessType.DELETE)
    public AjaxResult deleteBook(@Null(message = "请先选择")@RequestBody String ids){
        return service.deleteBook(ids);
    }

    /**
     * 更新图书
     * @param bookDto
     * @return
     */
    @RequestMapping("updateBook")
    @Log(title = "更新图书",businessType = BusinessType.UPDATE)
    public AjaxResult updateBook(@Validated @RequestBody BookDto bookDto){
        System.out.println(bookDto);
        return service.updateBook(bookDto);
    }

    /**
     * 出版社语言字典添加
     * @param sysDictData
     * @return
     * @throws ParseException
     */
    @RequestMapping("insertPublishAndLanguageDict")
    public AjaxResult insertPublishAndLanguageDict(@RequestBody SysDictData sysDictData) throws ParseException {
         return service.insertPublishAndLanguageDict(sysDictData);
    }
    /**
     * 出版社语言字典查询
     * @param sysDictData
     * @return
     * @throws ParseException
     */
    @RequestMapping("selectPublishAndLanguageDict")
    public AjaxResult selectPublishAndLanguageDict(@RequestBody SysDictData sysDictData){
        return service.selectPublishAndLanguageDict(sysDictData);
    }

    /**
     *
     * @param type
     * @return
     */
   @RequestMapping("selectBookAuthor")
    public AjaxResult selectBookAuthor(@NotNull @RequestBody(required = false) String type){
        return service.selectBookAuthor(type);
    }


    @RequestMapping("selectAuthorAndPublishDict")
    public AjaxResult selectAuthorAndPublishDict(@RequestBody(required = false) Dict dict){
            return service.selectAuthorAndPublishDict(dict);
    }

    @RequestMapping("addBookAuthor")
    public AjaxResult addBookAuthor (@RequestBody(required = false) String data) throws ParseException, JsonProcessingException {
        return service.addBookAuthor(data);
    }


    /**
     * 图片上传云服务器
     * @param file
     * @return Result
     */

    @RequestMapping("addUrl")
    public AjaxResult addUrl(@Null @RequestPart("file") MultipartFile file) throws IOException {
//        try {
//            // 处理上传的图片
//            byte[] imageData = file.getBytes();
//            // 在这里可以进一步处理二进制数据，例如保存到文件或云存储服务
//            System.out.println(imageData);
//
//            // 调用上传图片的方法，这里 QiniuImageUploader.uploadImage 返回上传后的图片 URL
//            String imageUrl = qiniuImageUploader.uploadImage(file);
////            String imageUrl = QiniuImageUploader.uploadImage(file);
//
//            // 返回上传成功后的图片 URL
//
//            return AjaxResult.success("图片上传云服务器成功",imageUrl);
////            return ResponseEntity.ok("Image uploaded successfully. URL: " + imageUrl);
//        } catch (Exception e) {
//            e.printStackTrace();
////            return ResponseEntity.status(500).body("Error uploading image.");
//            return AjaxResult.error("图片上传云服务器失败");
//        }
        String newFileName = null;
        String oldFileName = file.getOriginalFilename();
        String randomStr = UUID.randomUUID().toString();
        newFileName = randomStr + oldFileName.substring(oldFileName.lastIndexOf("."));
        String filePath = uploadPath + File.separator + "image" + File.separator + newFileName;
        File destFile = new File(filePath);
        if(!destFile.getParentFile().exists()){
            destFile.getParentFile().mkdirs();
        }
        file.transferTo(destFile);
        return AjaxResult.success(newFileName);
    }

    }


